
#include "memory.h"

struct mem_info minfo;
int is_mem_recording = 0;
FILE *mem_logger;
static char mem_filename[BUFFERSIZE];


static int r_is_mem_recording = 0;

void set_mem_logging()
{
    if (loggable && !r_is_mem_recording && is_mem_recording) {
        r_is_mem_recording = 1;
        char timesuffix[BUFFERSIZE];
        make_filename(timesuffix);
        snprintf(mem_filename, BUFFERSIZE, "%s/memory_%s.log", LOGGER_PATH, timesuffix);
        mem_logger = fopen(mem_filename, "w");
        if (mem_logger == NULL) {
            loggable = 0;
            // TODO notify UI that unable to create a file
            __android_log_print(ANDROID_LOG_INFO, LOG_TAG, "mem logging failed\n");
            return;
        }
        fprintf(mem_logger, "seconds  total  cache  free  buffer\n");
        __android_log_print(ANDROID_LOG_INFO, LOG_TAG, "mem logging started\n");
    } else if (r_is_mem_recording && !is_mem_recording) {
        r_is_mem_recording = 0;
        if (mem_logger == NULL) return;
        fclose(mem_logger);
        __android_log_print(ANDROID_LOG_INFO, LOG_TAG, "mem logging stopped\n");
        struct stat st;
        stat(mem_filename, &st);
        if (st.st_size == 0) {
            __android_log_print(ANDROID_LOG_INFO, LOG_TAG, "empty mem logging removed\n");
            remove(mem_filename);
        }
    }
}

void mem_cleanup()
{
    if (mem_logger != NULL) fclose(mem_logger);
}

void init_memory()
{
    memset(&minfo, 0, sizeof (minfo));
    is_mem_recording = 0;
}

void mem_dump()
{
    FILE *fp;
    char tmp[50];
    fp = fopen(MEMINFO, "r");
    if (fp == NULL) {
        //__android_log_print(ANDROID_LOG_INFO, LOG_TAG, "Cannot open /proc/memo\n");
        return;
    }
    fscanf(fp, "%s %lu %s", tmp, &minfo.memtotal, tmp);
    fscanf(fp, "%s %lu %s", tmp, &minfo.memfree, tmp);
    fscanf(fp, "%s %lu %s", tmp, &minfo.buffers, tmp);
    fscanf(fp, "%s %lu %s", tmp, &minfo.cached, tmp);
    fclose(fp);
    if (is_mem_recording && loggable) {
        fprintf(mem_logger, "%llu %lu %lu %lu %lu\n", (unsigned long long)time(NULL),
                minfo.memtotal, minfo.cached, minfo.memfree, minfo.buffers);
        fflush(mem_logger);
    }
}


unsigned long get_mem_total(void)
{
    return minfo.memtotal;
}

unsigned long get_mem_free(void)
{
    return minfo.memfree;
}

unsigned long get_mem_buffers(void)
{
    return minfo.buffers;
}

unsigned long get_mem_cached(void)
{
    return minfo.cached;
}

